using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using CodeStory.SmartUpload.WebControls;
using CodeStory.SmartUpload.WebControls;
using System.Web;

namespace CodeStory.SmartUpload
{
	internal class SmartField
	{
		string name = string.Empty;
		string fileName = string.Empty;
		string mimeType = string.Empty;
		int currentBufferPosition = -1;
		Guid guid = Guid.Empty;
		string tempFileName = string.Empty;
		HttpApplication application;
		SmartUploadContext currentUploadContext = null;

		public SmartUploadContext CurrentUploadContext {
			get {
				if (currentUploadContext == null) {
					currentUploadContext = SmartUploadContext.GetContext(Application.Context);
				}
				return currentUploadContext;
			}
		}

		public HttpApplication Application {
			get { return application; }
			set { application = value; }
		}
		public SmartField() {
		}

		internal string Name {
			get { return name; }
			set { name = value; }
		}

		internal string FileName {
			get { return fileName; }
			set { 
				fileName = value;
				CurrentUploadContext.SmartProgress.CurrentFileName = value;
			}
		}

		internal string MimeType {
			get { return mimeType; }
			set { mimeType = value; }
		}

		internal bool IsFile {
			get { return !string.IsNullOrEmpty(FileName); }
		}

		internal int CurrentBufferPosition {
			get { return currentBufferPosition; }
			set { currentBufferPosition = value; }
		}
		internal string TempFileName {
			get { return tempFileName; }
		}
		FileStream fs = null;

		internal void FlushData(byte[] data) {
			if (fs == null) {
				guid = Guid.NewGuid();
				string app = application.Context.Request.PhysicalApplicationPath;
				string temp = Path.Combine(app,SmartConfiguration.TempFilePath);
				tempFileName = Path.Combine(temp, guid.ToString() + Path.GetExtension(FileName));
				fs = File.Open(tempFileName, FileMode.Create);
			}
			fs.Write(data, 0, data.Length);
			fs.Flush();
			CurrentBufferPosition += data.Length;
		}

		internal void Close() {
			if (fs != null) {
				fs.Flush();
				fs.Close();
				fs.Dispose();
			}
			UploadFile f = new UploadFile();
			f.ClientFileName = FileName;
			f.MimeType = MimeType;
			f.TempFileName = TempFileName;
			f.Name = Name;
			//LoggingService.Info(FileName);
			AddUploadFile(f);
		}

		private void AddUploadFile(UploadFile f) {
			SmartUploadContext c = SmartUploadContext.GetContext(Application.Context);
			if (c == null) return;
			
			c.UploadFiles.Add(f);
		}

		internal void Abort() {
			if (fs != null) {
				fs.Close();
				fs.Dispose();
			}
			if (File.Exists(tempFileName)) {
				File.Delete(tempFileName);
			}
		}
	}
}
